package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.Category;
import com.example.domain.Dish;
import com.example.domain.DishFlavor;
import com.example.dto.DishDto;
import com.example.service.CategoryService;
import com.example.service.DishFlavorService;
import com.example.service.DishService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {


    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        Page p = (Page) redisTemplate.opsForValue().get("dishes");

        if (p != null) {
            return R.success(p);
        }

        Page<Dish> page1 = new Page<>(page, pageSize);

        Page<DishDto> page2 = new Page<>();

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<Dish>();

        wrapper.orderByDesc(Dish::getUpdateTime);

        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);


        dishService.page(page1, wrapper);

        BeanUtils.copyProperties(page1, page2, "records");

        List<Dish> records = page1.getRecords();

        List<DishDto> list = records.stream().map(dish -> {

            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish, dishDto);

            Long categoryId = dish.getCategoryId();

            Category byId = categoryService.getById(categoryId);

            if (byId != null) {
                dishDto.setCategoryName(byId.getName());
            }

            return dishDto;

        }).collect(Collectors.toList());

        page2.setRecords(list);

        redisTemplate.opsForValue().set("dishes", page2, 3600L, TimeUnit.SECONDS);

        return R.success(page2);

    }


    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {


        dishService.saveWithFlavor(dishDto);

        String key = "dish_list_" + dishDto.getCategoryId() + " " + 1;
        redisTemplate.delete(key);
        redisTemplate.delete("dishes");

        return R.success("添加成功！");


    }


    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {

        DishDto dishDtoWithFlavor = dishService.getDishDtoWithFlavor(id);

        return R.success(dishDtoWithFlavor);
    }


    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);

        String key = "dish_list_" + dishDto.getCategoryId() + " " + 1;
        redisTemplate.delete(key);
        redisTemplate.delete("dishes");

        return R.success("修改成功！");
    }

    @DeleteMapping
    public R<String> delete(Long[] ids) {

        for (Long id : ids) {
            dishService.deleteWithFlavor(id);
            Dish byId = dishService.getById(id);
            String key = "dish_list_" + byId.getCategoryId() + " " + 1;
            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
            }
        }

        redisTemplate.delete("dishes");
        return R.success("删除成功！");
    }


    @CacheEvict(value = "dishes", allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> change(@PathVariable Integer status, Long[] ids) {

        for (Long id : ids) {
            dishService.changeStatus(id, status);
            Dish byId = dishService.getById(id);
            String key = "dish_list_" + byId.getCategoryId() + " " + 1;
            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
            }
        }

        return R.success("修改成功！");
    }

//   @GetMapping("/list")
//    public R<List<Dish>> getDish(Dish dish){
//
//        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<Dish>();
//
//        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//
//        wrapper.eq(Dish::getStatus, 1);
//
//        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> list = dishService.list(wrapper);
//
//        return R.success(list);
//    }


    @GetMapping("/list")
    public R<List<DishDto>> getDish(Dish dish) {

        List<DishDto> dishDtos = null;

        String key = "dish_list_" + dish.getCategoryId() + " " + dish.getStatus();

        if (redisTemplate.hasKey(key)) {
            dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<Dish>();

        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        wrapper.eq(Dish::getStatus, 1);

        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(wrapper);

        dishDtos = list.stream().map(dishs -> {

            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dishs, dishDto);

            Long categoryId = dishs.getCategoryId();

            Category byId = categoryService.getById(categoryId);

            if (byId != null) {
                dishDto.setCategoryName(byId.getName());
            }

            Long id = dishs.getId();

            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<DishFlavor>();

            wrapper1.eq(DishFlavor::getDishId, id);

            List<DishFlavor> list1 = dishFlavorService.list(wrapper1);

            dishDto.setFlavors(list1);

            return dishDto;

        }).collect(Collectors.toList());


        redisTemplate.opsForValue().set(key, dishDtos, 60L, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }


}
